package impl

import "github.com/gorilla/websocket"

type Connection struct {
	wsConn     *websocket.Conn
	inChannel  chan []byte
	outChannel chan []byte
}

func InitConnection(wsConn *websocket.Conn) (conn *Connection, err error) {
	conn = &Connection{
		wsConn:     wsConn,
		inChannel:  make(chan []byte, 1000),
		outChannel: make(chan []byte, 1000),
	}

	//启动读协程
	go conn.readLoop()

	//启动写协程
	go conn.writeLoop()
	return
}

//API
func (conn *Connection) ReadMessage() (data []byte, err error) {
	data = <-conn.inChannel
	return
}
func (conn *Connection) WriteMessage(data []byte) (err error) {
	conn.outChannel <- data
	return
}
func (conn *Connection) Close() {
	// 线程安全的，可重入的Close。
	conn.wsConn.Close()
}

//内部实现
func (conn *Connection) readLoop() { //这个读协程 在不停的读长连接上的消息，读到了就放到inChannel里面
	var (
		data []byte
		err  error
	)

	for {
		if _, data, err = conn.wsConn.ReadMessage(); err != nil {
			goto ERR
		}
		conn.inChannel <- data
	}
ERR:
	conn.Close()
}

func (conn *Connection) writeLoop() {
	var (
		data []byte
		err  error
	)
	for {
		data = <-conn.outChannel
		if conn.wsConn.WriteMessage(websocket.TextMessage, data); err != nil {
			goto ERR
		}
	}
ERR:
	conn.Close()
}
